<template>
  <div class="compare-analysis">
    <a-card title="教学质量对比分析">
      <a-form layout="inline" :form="form" style="margin-bottom: 16px;">
        <a-form-item label="对比维度">
          <a-select 
            v-decorator="['dimension', { initialValue: 'teacher' }]"
            style="width: 150px"
            @change="handleDimensionChange"
          >
            <a-select-option value="teacher">教师对比</a-select-option>
            <a-select-option value="course">课程对比</a-select-option>
            <a-select-option value="department">部门对比</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="选择对象">
          <a-select
            mode="multiple"
            v-decorator="['items', { rules: [{ required: true, message: '请至少选择两个对比对象' }] }]"
            style="width: 300px"
            placeholder="请选择对比对象"
            :loading="loadingOptions"
          >
            <a-select-option 
              v-for="item in selectOptions" 
              :key="item.id"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="评价类型">
          <a-select
            v-decorator="['evaluateType', { initialValue: 'total' }]"
            style="width: 150px"
          >
            <a-select-option value="total">综合评分</a-select-option>
            <a-select-option value="student">学生评价</a-select-option>
            <a-select-option value="supervisor">督导评价</a-select-option>
            <a-select-option value="peer">同行评价</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item>
          <a-button 
            type="primary" 
            @click="handleCompare"
            :loading="comparing"
          >
            开始对比
          </a-button>
        </a-form-item>
      </a-form>

      <a-alert
        v-if="showChart && compareData.length > 0"
        message="分析提示"
        description="点击图表中的图例可以显示/隐藏对应的数据系列"
        type="info"
        show-icon
        style="margin-bottom: 16px;"
      />

      <div v-if="showChart" class="chart-container">
        <a-tabs default-active-key="1">
          <a-tab-pane key="1" tab="评分对比">
            <div class="chart-wrapper">
              <bar-chart 
                :data="scoreChartData"
                :height="400"
              />
            </div>
          </a-tab-pane>
          
          <a-tab-pane key="2" tab="趋势对比">
            <div class="chart-wrapper">
              <line-chart 
                :data="trendChartData"
                :height="400"
              />
            </div>
          </a-tab-pane>
          
          <a-tab-pane key="3" tab="详细数据">
            <a-table
              :columns="detailColumns"
              :dataSource="compareData"
              :pagination="false"
              size="middle"
            >
              <template slot="score" slot-scope="text">
                <a-tag :color="getScoreColor(text)">
                  {{ text }}分
                </a-tag>
              </template>
              <template slot="trend" slot-scope="text">
                <span :class="getTrendClass(text)">
                  <a-icon :type="text > 0 ? 'arrow-up' : 'arrow-down'" />
                  {{ Math.abs(text) }}%
                </span>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </div>
      
      <a-empty
        v-else-if="showChart"
        description="暂无对比数据"
        style="margin-top: 40px;"
      />
    </a-card>
  </div>
</template>

<script>
import BarChart from '@/components/Charts/ChartBar.vue';
import LineChart from '@/components/Charts/ChartLine.vue';

export default {
  components: {
    BarChart,
    LineChart
  },
  data() {
    return {
      form: this.$form.createForm(this),
      loadingOptions: false,
      comparing: false,
      selectOptions: [],
      compareData: [],
      showChart: false,
      detailColumns: [
        { title: '名称', dataIndex: 'name', key: 'name' },
        { title: '当前评分', dataIndex: 'currentScore', key: 'currentScore', scopedSlots: { customRender: 'score' } },
        { title: '上期评分', dataIndex: 'lastScore', key: 'lastScore', scopedSlots: { customRender: 'score' } },
        { title: '变化趋势', dataIndex: 'trend', key: 'trend', scopedSlots: { customRender: 'trend' } }
      ]
    };
  },
  computed: {
    scoreChartData() {
      if (!this.compareData.length) return null;
      
      return {
        labels: ['综合评分', '学生评价', '督导评价', '同行评价'],
        datasets: this.compareData.map(item => ({
          label: item.name,
          data: [
            item.totalScore,
            item.studentScore,
            item.supervisorScore,
            item.peerScore
          ],
          backgroundColor: this.getChartColor(item.id),
          borderColor: this.getChartColor(item.id),
          borderWidth: 1
        }))
      };
    },
    trendChartData() {
      if (!this.compareData.length) return null;
      
      return {
        labels: ['上学期', '本学期'],
        datasets: this.compareData.map(item => ({
          label: item.name,
          data: [item.lastScore, item.currentScore],
          backgroundColor: 'transparent',
          borderColor: this.getChartColor(item.id),
          borderWidth: 2,
          pointBackgroundColor: this.getChartColor(item.id),
          pointRadius: 5,
          pointHoverRadius: 7
        }))
      };
    }
  },
  created() {
    this.fetchOptions();
  },
  methods: {
    async fetchOptions() {
      this.loadingOptions = true;
      try {
        // 模拟API请求
        await new Promise(resolve => setTimeout(resolve, 500));
        
        const dimension = this.form.getFieldValue('dimension') || 'teacher';
        if (dimension === 'teacher') {
          this.selectOptions = [
            { id: 'T1001', name: '王芳' },
            { id: 'T1002', name: '李廷' },
            { id: 'T1003', name: '王雪' },
            { id: 'T1004', name: '陈立伟' },
            { id: 'T1005', name: '钱老师' }
          ];
        } else if (dimension === 'course') {
          this.selectOptions = [
            { id: 'C2001', name: '数据结构' },
            { id: 'C2002', name: '算法分析' },
            { id: 'C2003', name: '操作系统' },
            { id: 'C2004', name: '计算机网络' },
            { id: 'C2005', name: '数据库原理' }
          ];
        } else {
          this.selectOptions = [
            { id: 'D001', name: '信息工程系' },
            { id: 'D002', name: '机电工程系' },
            { id: 'D003', name: '建筑工程系' },
            { id: 'D004', name: '机电工程系' },
            { id: 'D005', name: '经济学院' }
          ];
        }
      } catch (error) {
        console.error('获取选项失败:', error);
        this.$message.error('获取对比选项失败');
      } finally {
        this.loadingOptions = false;
      }
    },
    handleDimensionChange() {
      this.form.setFieldsValue({ items: [] });
      this.showChart = false;
      this.fetchOptions();
    },
    handleCompare() {
      this.form.validateFields(async (err, values) => {
        if (err) return;
        
        if (values.items.length < 2) {
          this.$message.warning('请至少选择两个对比对象');
          return;
        }
        
        this.comparing = true;
        this.showChart = true;
        
        try {
          // 模拟API请求
          await new Promise(resolve => setTimeout(resolve, 800));
          
          // 生成模拟数据
          this.compareData = values.items.map(id => {
            const item = this.selectOptions.find(opt => opt.id === id);
            const baseScore = Math.floor(Math.random() * 20) + 75;
            const trend = (Math.random() * 10 - 5).toFixed(1);
            
            return {
              id: item.id,
              name: item.name,
              totalScore: baseScore,
              studentScore: baseScore + Math.floor(Math.random() * 5) - 2,
              supervisorScore: baseScore + Math.floor(Math.random() * 5) - 2,
              peerScore: baseScore + Math.floor(Math.random() * 5) - 2,
              currentScore: baseScore,
              lastScore: baseScore - trend,
              trend: parseFloat(trend)
            };
          });
        } catch (error) {
          console.error('获取对比数据失败:', error);
          this.$message.error('获取对比数据失败');
        } finally {
          this.comparing = false;
        }
      });
    },
    getScoreColor(score) {
      if (score >= 90) return 'green';
      if (score >= 80) return 'blue';
      if (score >= 70) return 'orange';
      return 'red';
    },
    getTrendClass(trend) {
      return trend > 0 ? 'up' : trend < 0 ? 'down' : '';
    },
    getChartColor(id) {
      const colors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1'];
      const index = this.selectOptions.findIndex(opt => opt.id === id) % colors.length;
      return colors[index];
    }
  }
};
</script>

<style scoped>
.compare-analysis {
  padding: 16px;
}
.chart-container {
  margin-top: 20px;
}
.chart-wrapper {
  background: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.up {
  color: #52c41a;
}
.down {
  color: #f5222d;
}
</style>